import { Row, Col, Transfer, Input, Tabs, Spin, message } from 'antd';
import React, { useState, useEffect, useCallback } from 'react';
import TreeControlled from '@/components/blocks/TreeControlled';
import { useRequest } from '@umijs/hooks';
import { getDepartmentTreeByRole, findUserByDepartmentId } from '../../service';

export default function Step3(props) {
  const {
    data = {},
    targetKeys,
    setTargetKeys,
    loading: checkedLoading,
    setSelectUsers,
    selectUsers,
  } = props;
  const [dept, setDept] = useState({});
  const [preUserData, setPreUserData] = useState([]);
  const [userData, setUserData] = useState([]);
  const competence = data.competence;

  const { loading, data: deptData = [] } = useRequest(getDepartmentTreeByRole, {
    onSuccess: ([root]) => {
      setSelectedKeys([root.key]);
      setDept(root);
    },
  });
  const { loading: userLoading, run } = useRequest(findUserByDepartmentId, {
    manual: true,
    onSuccess(res) {
      let users = [...selectUsers];
      if (res && res.length > 0) {
        users = users.concat(
          res.filter(item => selectUsers.every(innerItem => innerItem.key !== item.key)),
        );
      }
      users = users.map(item => ({
        ...item,
        warning: item.disabled ? '当用户已包含管理员角色时，用户不可选中' : '',
      }));
      setPreUserData(users);
      if (competence === '0' && selectUsers.length > 0) {
        setUserData(
          users.map(item => ({
            ...item,
            disabled: item.disabled || !selectUsers.some(innerItem => innerItem.key === item.key),
            title: item.title || ' '
          })),
        );
      } else {
        let resetUsers = users;
        resetUsers.map(item => item.title = item.title || ' ')
        setUserData(resetUsers);
      }
    },
  });

  const [inited, setInited] = useState(false);
  useEffect(() => {
    if (!inited) {
      setInited(true);
    } else if (dept.key && competence) {
      run({ toId: dept.key, competence });
    }
  }, [dept.key, inited, run, competence]);

  const [selectedKeys, setSelectedKeys] = useState([]);
  const onSelect = function onSelect(keys, { selected, node }) {
    if (selected) {
      setDept({ ...node.props, key: node.props.eventKey });
      setSelectedKeys(keys);
    }
  };

  const [searchValue, setSearchValue] = useState('');
  const [expandedKeys, setExpandedKeys] = useState([]);

  // 树结构展开
  const getExpandedKeysWithValue = function getExpandedKeysWithValue(tree, value, parentKeys) {
    if (!tree) {
      return [];
    }
    return tree.reduce((pre, cur) => {
      if (~cur.title.indexOf(value)) {
        const childKeys = getExpandedKeysWithValue(cur.children, value, [cur.key]);
        return pre.concat([...parentKeys, ...childKeys]);
      } else {
        return pre.concat(getExpandedKeysWithValue(cur.children, value, [cur.key, ...parentKeys]));
      }
    }, []);
  };

  const onSearch = useCallback(
    e => {
      setSearchValue(e.target.value);
      // 树结构展开搜索
      const expandedKeys = getExpandedKeysWithValue(deptData, e.target.value, []);
      setExpandedKeys(expandedKeys);
    },
    [deptData],
  );

  const renderTitle = useCallback(
    ({ title }) => {
      const matched = ''.match.call(title, `(.*)(${searchValue})(.*)`);
      return matched ? (
        <>
          {matched[1]}
          {matched.length > 2 && <span style={{ color: '#E13B3B' }}>{matched[2]}</span>}
          {matched.length > 3 && matched[3]}
        </>
      ) : (
          title
        );
    },
    [searchValue],
  );

  const onChange = useCallback(
    (keys, direction, moveKeys) => {
      if (direction === 'right') {
        setSelectUsers(
          selectUsers.concat(moveKeys.map(key => userData.find(item => item.key === key))),
        );
        if (competence === '0') {
          if (moveKeys.length > 1) {
            message.warning('不能设置多个管理员');
            return;
          }
          setUserData(
            preUserData.map(item => ({
              ...item,
              disabled: item.disabled || !keys.some(key => key === item.key),
              title: item.title || ' '
            })),
          );
        }
      } else {
        setSelectUsers(selectUsers.filter(key => moveKeys.some(innerKey => key === innerKey)));
        if (competence === '0' && keys.length === 0) {
          let resetPreUserData = preUserData;
          resetPreUserData.map(item => item.title = item.title || ' ')
          setUserData(resetPreUserData);
        }
      }
      setTargetKeys(keys);
    },
    [setTargetKeys, setSelectUsers, userData, selectUsers, competence, setUserData, preUserData],
  );

  return (
    <Tabs>
      <Tabs.TabPane tab="用户分配" key="_1">
        <Row gutter={16}>
          <Col span={8} style={{ paddingLeft: 24 }}>
            <Input.Search
              disabled={loading}
              style={{ marginBottom: 8 }}
              placeholder="搜索部门名称"
              onChange={onSearch}
              value={searchValue}
            />
            <Spin spinning={loading}>
              <div style={{ height: 300, overflow: 'auto' }}>
                <TreeControlled
                  data={deptData}
                  selectable
                  renderTitle={renderTitle}
                  expandedKeys={expandedKeys}
                  setExpandedKeys={setExpandedKeys}
                  selectedKeys={selectedKeys}
                  setSelectedKeys={onSelect}
                />
              </div>
            </Spin>
          </Col>
          <Col span={16}>
            <Spin spinning={userLoading || checkedLoading}>

              <Transfer
                dataSource={userData}
                titles={['全部用户', '已选用户']}
                showSearch
                listStyle={{
                  width: 240,
                  height: 340,
                }}
                targetKeys={targetKeys}
                onChange={onChange}
                render={item => item.title}
                // render={item => (
                //   <span
                //     title={
                //       item.warning
                //         ? item.warning
                //         : item.disabled
                //           ? '只能添加一个管理员'
                //           : item.title
                //     }
                //   >
                //     {item.title}
                //   </span>
                // )}
              />
            </Spin>
          </Col>
        </Row>
      </Tabs.TabPane>
    </Tabs>
  );
}
